﻿#Region "阻止用户多线程下载同一文件"
Imports System.Threading

Public Class C_Pervent_Mulite_Thread_DownLoad_File
    Dim usersRWLS As New ReaderWriterLock
    Dim FileIDItems As New List(Of Struct_FileIDItem)

    Public Structure Struct_FileIDItem
        Dim ConnID As IntPtr
        Dim User_Agent As String
        Dim User_IP As String
        Dim User_Port As UShort
        Dim FilePath As String
        Public Sub New(ConnID As IntPtr, User_Agent As String, User_IP As String, User_Port As String, FilePath As String)
            Me.ConnID = ConnID
            Me.User_Agent = User_Agent
            Me.FilePath = FilePath
        End Sub
    End Structure
    Public Sub AddItem(FileIDItem As Struct_FileIDItem)
        Try
            usersRWLS.AcquireWriterLock(3000)
            FileIDItems.Add(FileIDItem)
        Catch ex As Exception
        Finally
            If usersRWLS.IsWriterLockHeld Then usersRWLS.ReleaseWriterLock()
        End Try
    End Sub
    Public Sub DeleteItem(FileIDItem As Struct_FileIDItem)
        Try
            usersRWLS.AcquireWriterLock(3000)
            Try
                FileIDItems.Remove(FileIDItem)
            Catch ex As Exception

            End Try
        Catch ex As Exception
        Finally
            If usersRWLS.IsWriterLockHeld Then usersRWLS.ReleaseWriterLock()
        End Try
    End Sub
    Public Function CheckIsMulitThread(FileIDItem As Struct_FileIDItem) As Boolean
        Try
            usersRWLS.AcquireReaderLock(3000)
            For Each item In FileIDItems
                If item.User_Agent = FileIDItem.User_Agent And item.FilePath = FileIDItem.FilePath Then
                    Return True
                End If
            Next
            Return False
        Catch ex As Exception
            Return False
        Finally
            If usersRWLS.IsReaderLockHeld Then usersRWLS.ReleaseReaderLock()
        End Try
    End Function


End Class
#End Region